package com.n9.echo.test;

import com.n9.qq.client.AbstractClient;
import com.n9.qq.client.AbstractProtocol;
import com.n9.qq.client.FromServiceMsg;
import com.n9.qq.client.ToServiceMsg;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.*;
import org.junit.Test;

import java.io.IOException;

/**
 * @author ice
 * @since 2019/1/31 17:27
 */
public class EchoClient {

    @Test
    public void testEcho() throws IOException {
        AbstractProtocol protocol = new AbstractProtocol() {
            @Override
            protected boolean doDecode(IoSession ioSession, IoBuffer ioBuffer, ProtocolDecoderOutput protocolDecoderOutput) throws Exception {
                byte[] data = new byte[ioBuffer.remaining()];
                ioBuffer.get(data);

                FromServiceMsg fromServiceMsg = new EchoFromServiceMsg();
                fromServiceMsg.read(data);

                protocolDecoderOutput.write(fromServiceMsg);
                return true;
            }

            @Override
            public void encode(IoSession ioSession, Object o, ProtocolEncoderOutput protocolEncoderOutput) throws Exception {
                if (o instanceof ToServiceMsg) {
                    ToServiceMsg toServiceMsg = (ToServiceMsg) o;
                    byte[] bytes = toServiceMsg.getBytes();

                    IoBuffer buf = IoBuffer.allocate(bytes.length);
                    buf.setAutoExpand(true);
                    buf.put(bytes);
                    buf.flip();

                    protocolEncoderOutput.write(buf);
                }
            }
        };

        AbstractClient client = new AbstractClient("localhost", 19999, protocol) {
            @Override
            public void handle(FromServiceMsg fromServiceMsg) {
            }
        };

        EchoToServiceMsg toServiceMsg = new EchoToServiceMsg(1, "hello server i'm mina");
        EchoFromServiceMsg fromServiceMsg = (EchoFromServiceMsg) client.send(toServiceMsg, 1000);
        if (fromServiceMsg != null) {
            System.out.println(fromServiceMsg.getMsg());
        }
        client.close();
    }
}
